﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using TheHeGeoDao;

namespace TheHeGeoManager.Uc
{
    public partial class UcEqTracker : UcBase
    {
        public UcEqTracker()
        {
            InitializeComponent();
            cbbFilter.SelectedIndex = 1;
        }

        private void btReLoad_Click(object sender, EventArgs e)
        {
            Reload();
        }

        protected void LoadGrvErrorData()
        {
            try
            {
                var ent = (from p in DaoHelper.Entities.ThietBis
                    join d in DaoHelper.Entities.DuAns on p.MaDuAn equals d.MaDuAn
                    where (
                        (p.LastUpdate.HasValue ||
                         p.LastUpdate.Value < DbFunctions.AddSeconds(DateTime.Now, -((int) (p.TgLayMau*2))))
                        && p.Status == 0
                        )
                    select new
                    {
                        p.MaThietBi,
                        p.TenThietBi,
                        p.MoTa,
                        p.LastUpdate,
                        d.MaDuAn,
                        d.TenDuAn
                    }).ToList();

                gridCtrl.DataSource = ent;
            }
            catch (Exception)
            {
                gridCtrl.DataSource = null;
            }
        }

        protected void LoadGrvDataAll()
        {
            gridCtrl.DataSource =(from p in DaoHelper.Entities.ThietBis 
                                  join d in DaoHelper.Entities.DuAns on p.MaDuAn equals d.MaDuAn
                                  select new
                                {
                                    p.MaThietBi,
                                    p.TenThietBi,
                                    p.MoTa,
                                    p.LastUpdate,
                                    d.MaDuAn,
                                    d.TenDuAn
                                }).ToList();
        }

        protected void Reload()
        {
            if (cbbFilter.SelectedIndex == 0)
            {
                LoadGrvDataAll();
            }
            else
            {
                LoadGrvErrorData();
            }
        }

        private void cbbFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            Reload();
        }
    }
}
